package com.woniu.service.mallSystem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mapper.mallSystem.AddressMapper;
import com.woniu.mapper.mallSystem.CommodityMapper;
import com.woniu.mapper.mallSystem.OrderItemMapper;
import com.woniu.mapper.mallSystem.OrderMapper;
import com.woniu.model.gh.common.enums.OrderStatusEnum;
import com.woniu.model.gh.common.enums.impl.ResultCode;
import com.woniu.model.gh.common.exception.Asserts;
import com.woniu.model.mallSystem.dto.OrderDto;
import com.woniu.model.mallSystem.entity.Commodity;
import com.woniu.model.mallSystem.entity.Order;
import com.woniu.model.mallSystem.entity.OrderItem;
import com.woniu.model.mallSystem.vo.OrderItemVo;
import com.woniu.model.mallSystem.vo.OrderQueryVo;
import com.woniu.model.mallSystem.vo.OrderVo;
import com.woniu.model.mallSystem.vo.PageVo;
import com.woniu.service.mallSystem.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Lzj
 * @since 2023-10-19
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 导出订单列表
     */
    @Override
    public List<OrderVo> findAll() {
        return orderMapper.findAll();
    }

    /**分页
     * 根据订单编号模糊查询、用户账号模糊查询、精确订单状态查询
     * SELECT * FROM t_order  WHERE order_number like '%3665%' and t_user_id like '%3%' and order_status = '1'
     */
    /**
     * 查询所有订单分页
     */
    @Override
    public PageVo findAllOrder(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class);
        Page<Order> orderPage = baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageVo<>(orderPage.getRecords(), orderPage.getTotal());
    }

    /**
     * 高级查询订单分页
     */
    @Override
    public PageVo advancedQuery(Integer pageNum, Integer pageSize, OrderQueryVo orderQueryVo) {
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class);
        wrapper.like(orderQueryVo.getOrderNumber() != null, Order::getOrderNumber, orderQueryVo.getOrderNumber())
                .like(orderQueryVo.getUserId() != null, Order::getUserId, orderQueryVo.getUserId())
                .eq(orderQueryVo.getOrderSource() != null, Order::getOrderOrigin, orderQueryVo.getOrderSource())
                .eq(orderQueryVo.getState() != null, Order::getOrderStatus, orderQueryVo.getState())
                .ge(orderQueryVo.getStartDate() != null, Order::getCreateTime, orderQueryVo.getStartDate())
                .le(orderQueryVo.getEndDate() != null, Order::getCreateTime, orderQueryVo.getEndDate());
        Page<Order> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageVo(page.getRecords(), page.getTotal());
    }

    /**
     * 根据订单id查项目
     *
     */
    @Override
    public List<OrderItemVo> findItemByOrderId(Long id) {
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery(Order.class);
        //订单失效
        wrapper.eq(Order::getId,id).ne(Order::getOrderStatus, OrderStatusEnum.ORDER_EXPIRATION.getCode());
        Order order = orderMapper.selectOne(wrapper);
        if (Objects.isNull(order)) {
            return null;
        }
        //订单项的查询
        LambdaQueryWrapper<OrderItem> orderItemWrapper = Wrappers.lambdaQuery(OrderItem.class).eq(OrderItem::getOrderId,id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemWrapper);
        //转换vo
        ArrayList<OrderItemVo> orderItemVoList = new ArrayList<>();
        for (OrderItemVo itemVo : orderItemVoList) {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setId(itemVo.getId());
            orderItemVo.setCommodityName(itemVo.getCommodityName());
            //根据Item项找这个商品的图片
            // 设置图片字符段
            orderItemVo.setSrcImg(findImgByCommodityId(itemVo.getCommodityId()));
            orderItemVo.setBuyCount(itemVo.getBuyCount());
            orderItemVo.setSumprice(itemVo.getSumprice());
            orderItemVoList.add(orderItemVo);
        }
        return orderItemVoList;
    }

    // 定义一个新的方法来获取商品图片
    @Override
    public String findImgByCommodityId(Long id) {
        // 创建查询条件
        QueryWrapper<Commodity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        // 执行查询
        Commodity commodity = commodityMapper.selectOne(wrapper);
        // 返回商品图片，如果没有找到则返回空字符串
        return commodity != null ? commodity.getImgId().toString() : "";
    }


    /**
     * -----------------------------
     * ---------------------·------·
     */
    @Override
    public OrderVo selectById(Integer orderId) {
        OrderVo orderVo = orderMapper.getById(orderId);
        if (orderVo.getProvince().equals("中国")) {
            orderVo.setProvince("");
        }
        System.out.println("orderVo = " + orderVo);
        orderVo.setTotalPrice(orderVo.getTotalPrice().multiply(new BigDecimal(orderVo.getBuyCount())));
        return orderVo;
    }

    @Override
    public Page<OrderVo> getPageInfo(Integer pageSize, Integer pageNum, Integer orderStatus) {
        Page<OrderVo> page = Page.of(pageNum, pageSize);
        Page<OrderVo> pageInfo = orderMapper.getPageInfo(page, orderStatus);

        pageInfo.getRecords().stream().forEach(e -> {
            e.setTotalPrice(e.getTotalPrice().multiply(new BigDecimal(e.getBuyCount())));
        });
        System.out.println("pageInfo = " + pageInfo);
        return pageInfo;
    }

    @Override
    public List<OrderDto> getByIds(List<Integer> ids) {
        Asserts.error(ids.size() == 0, ResultCode.FAIL);
        List<OrderDto> orderDtoList = orderMapper.getByIds(ids);
        return orderDtoList;
    }
}
